package com.cll.prototype.user.controller;


import com.cll.prototype.common.dictionary.AjaxResultEnum;
import com.cll.prototype.common.dto.AjaxResult;
import com.cll.prototype.common.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 用户服务的表 前端控制器
 * </p>
 *
 * @author CLL
 * @since 2020-10-26
 */
@RestController
@RequestMapping("/user/user")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;

    /**
     * 用户注册
     * @param email 邮箱号
     * @param password  密码
     * @param confirmPassword   确认密码
     * @param captcha   验证码
     * @return  注册结果
     */
    @PostMapping(value = "/registry")
    public AjaxResult registry(@RequestParam("email") String email,
                               @RequestParam("password") String password,
                               @RequestParam("confirmPassword") String confirmPassword,
                               @RequestParam("captcha") String captcha,
                               HttpServletResponse response){
        try {
            AjaxResult registryResult = userService.add(email, password, confirmPassword, captcha);
            if (null != registryResult && AjaxResultEnum.SUCCESS.getCode() == registryResult.getCode() && null != registryResult.getData()) {
                Cookie cookie = new Cookie("token", registryResult.getData().toString());
                response.addCookie(cookie);
            }
            return registryResult;
        } catch (Exception e) {
            LOGGER.error("******用户注册抛出异常" + e.getMessage(), e);
            return AjaxResult.error(50, "注册失败");
        }
    }

    /**
     * 检测邮箱是否注册
     * @param email 邮箱号码
     * @return  检测结果
     */
    @PostMapping(value = "/isRegistry")
    public AjaxResult isRegistry(@RequestParam("email") String email){
        LOGGER.info("===>>> 检测邮箱是否已经注册。");
        try {
            return userService.isRegistry(email);
        } catch (Exception e) {
            LOGGER.error("****** 检测邮箱是否注册抛出异常" + e.getMessage(), e);
            return AjaxResult.error(52, "检测失败");
        }
    }



}
